package com.imooc.web;

import com.imooc.bo.SubmitOrderBo;
import com.imooc.enums.OrderStatusEnum;
import com.imooc.pojo.OrderStatus;
import com.imooc.pojo.Orders;
import com.imooc.service.OrderService;
import com.imooc.utils.CookieUtils;
import com.imooc.utils.Result;
import com.imooc.vo.MerchantOrdersVO;
import com.imooc.vo.OrderVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Authorization;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * <h1></h1>
 *
 * @author : dzj
 * @create: 2022-02-21 11:19
 */
@RestController
@RequestMapping("/orders")
@Api(value = "订单相关服务",tags = {"订单相关接口api"})
public class OrderController extends BaseController{

    @Autowired
    private OrderService orderService;
    @Autowired
    private RestTemplate restTemplate;
@PostMapping("/create")
@ApiOperation(value = "创建订单", notes = "创建订单" , httpMethod = "POST")

    public Result create(@RequestBody @Valid SubmitOrderBo submitOrderBo,
                         HttpServletRequest request,
                         HttpServletResponse response) {
        // 1. 创建订单
        OrderVO order = orderService.createOrder(submitOrderBo);
        //2 . 删除对应的购物车
        //todo 整合redis之后, 完善购物车中已结算商品清除,同步到前端cookie
        CookieUtils.setCookie(request,response,FOODIE_SHOPCART,"");

        //3. 向支付中心发送订单, 用于把偶才能支付中心订单数据
        order.getMerchantOrdersVO().setReturnUrl(payReturnUrl);
        order.getMerchantOrdersVO().setAmount(1);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("imoocUserId","imooc");
    headers.add("password","imooc");
    HttpEntity<MerchantOrdersVO> httpEntity = new HttpEntity<>(order.getMerchantOrdersVO(),headers);
    ResponseEntity<Result> responseEntity=restTemplate.postForEntity(paymentUrl,httpEntity,Result.class);
    Result body = responseEntity.getBody();
    if(body.getStatus()!=200) {
        //发生错误
        return Result.errorMsg("支付中心订单创建失败, 请联系管理员");
    }
    return Result.ok(order.getOrderId());
    }
    @PostMapping("notifyMerchantOrderPaid")
    public Integer notifyMerchantOrderPaid(String merchantOrderId) {
        orderService.updateOrderStatus(merchantOrderId, OrderStatusEnum.PAYED.code);
        return HttpStatus.OK.value();
    }

    @PostMapping("getPaidOrderInfo")
    public Result getPaidOrderInfo(String orderId) {
        OrderStatus orderStatus = orderService.queryOrderInfo(orderId);
        return Result.ok(orderStatus);
    }

}
